import React, { useRef, useContext } from 'react';
import * as XLSX from 'xlsx';
import { GradeLevel, StudentStatus } from '../../../shared/models';
import { DataContext } from '../../../shared/DataContext';

interface ImportModalProps {
  isOpen: boolean;
  onClose: () => void;
  classes: any[];
  onImportComplete?: () => void;
}

// 解析日期函数 - 增强版，支持更多格式和更健壮的错误处理
const parseDate = (date: any): string | null => {
  if (!date) return null;
  
  try {
    // 如果已经是Date对象
    if (date instanceof Date) {
      if (!isNaN(date.getTime())) {
        return date.toISOString();
      }
      return null;
    }
    
    // 如果是数字（Excel日期格式）
    if (typeof date === 'number' && !isNaN(date)) {
      // Excel的日期起始于1900年1月1日，但是有一个错误的闰年
      const millisecondsPerDay = 24 * 60 * 60 * 1000;
      // 处理Excel的1900年闰年错误（Excel认为1900年是闰年）
      if (date <= 60) {
        // 对于前60天的特殊处理，因为Excel错误地包含了1900年2月29日
        const excelEpoch = new Date(Date.UTC(1899, 11, 30)); // 1900-01-00
        const result = new Date(excelEpoch.getTime() + date * millisecondsPerDay);
        return result.toISOString();
      } else {
        // 对于60天以后的日期，需要减去1天来修正Excel的错误
        const excelEpoch = new Date(Date.UTC(1899, 11, 30)); // 1900-01-00
        const result = new Date(excelEpoch.getTime() + (date - 1) * millisecondsPerDay);
        return result.toISOString();
      }
    }
    
    // 字符串格式日期
    const dateStr = String(date).trim();
    
    // 空字符串或非有效字符串
    if (!dateStr || dateStr.toLowerCase() === 'null' || dateStr.toLowerCase() === 'undefined') {
      return null;
    }
    
    // 尝试几种常见的日期格式
    const dateFormats = [
      // ISO格式和变种
      /^(\d{4})-(\d{2})-(\d{2})$/ ,               // 2023-12-31
      /^(\d{4})\/(\d{2})\/(\d{2})$/ ,               // 2023/12/31
      /^(\d{2})\/(\d{2})\/(\d{4})$/ ,               // 31/12/2023
      /^(\d{4})(\d{2})(\d{2})$/ ,                    // 20231231
      /^(\d{4})-(\d{1,2})-(\d{1,2})$/ ,             // 2023-1-31
      /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/ ,             // 31/1/2023
      
      // 带时间的格式
      /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/, // ISO 8601 with time
      /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/, // 2023-12-31 23:59:59
      /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})/,          // 2023-12-31 23:59
      
      // 中文日期格式
      /^(\d{4})年(\d{1,2})月(\d{1,2})日$/ ,             // 2023年12月31日
      /^(\d{4})年(\d{1,2})月(\d{1,2})日\s*(\d{1,2}):(\d{1,2})/, // 2023年12月31日 23:59
    ];
    
    for (const format of dateFormats) {
      const match = dateStr.match(format);
      if (match) {
        let year, month, day;
        
        // 根据不同的格式提取年、月、日
        if (format.source.startsWith('^(\\d{4})-(\\d{2})-(\\d{2})') || 
            format.source.startsWith('^(\\d{4})\\/(\\d{2})\\/(\\d{2})') ||
            format.source.startsWith('^(\\d{4})(\\d{2})(\\d{2})') ||
            format.source.startsWith('^(\\d{4})-(\\d{1,2})-(\\d{1,2})') ||
            format.source.startsWith('^(\\d{4})年(\\d{1,2})月(\\d{1,2})日')) {
          // 以年份开头的格式
          year = match[1];
          month = match[2];
          day = match[3];
        } else if (format.source.startsWith('^(\\d{2})\\/(\\d{2})\\/(\\d{4})') ||
                   format.source.startsWith('^(\\d{1,2})\\/(\\d{1,2})\\/(\\d{4})')) {
          // 以日期开头的格式 (31/12/2023)
          day = match[1];
          month = match[2];
          year = match[3];
        }
        
        // 创建日期对象并验证
        const dateObj = new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
        
        // 额外验证日期是否有效（防止2月30日这样的无效日期）
        if (!isNaN(dateObj.getTime()) && 
            dateObj.getFullYear() === parseInt(year) && 
            dateObj.getMonth() + 1 === parseInt(month) && 
            dateObj.getDate() === parseInt(day)) {
          return dateObj.toISOString();
        }
      }
    }
    
    // 尝试使用Date构造函数直接解析（作为最后的手段）
    // 先尝试去除可能的干扰字符
    const cleanedDateStr = dateStr.replace(/[,，]/g, '-').replace(/[\s]+/g, ' ').trim();
    const dateObj = new Date(cleanedDateStr);
    
    // 验证日期是否有效
    if (!isNaN(dateObj.getTime())) {
      return dateObj.toISOString();
    }
  } catch (error) {
    console.error('Date parsing error:', error);
  }
  
  return null;
};

const ImportModal: React.FC<ImportModalProps> = ({ 
  isOpen, 
  onClose, 
  classes, 
  onImportComplete 
}) => {
  const dataContext = useContext(DataContext);
  
  if (!dataContext) {
    throw new Error('ImportModal must be used within a DataProvider');
  }
  
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [importData, setImportData] = React.useState<any[]>([]);
  const [importErrors, setImportErrors] = React.useState<string[]>([]);
  const [importSuccess, setImportSuccess] = React.useState<number>(0);
  const [isImporting, setIsImporting] = React.useState(false);

  // 验证导入数据
  const validateImportData = (data: any[]) => {
    const validatedData: any[] = [];
    const errors: string[] = [];
    const existingStudentIds = new Set(); // 暂时为空，实际应该从API获取
    
    // 检查是否有数据
    if (!Array.isArray(data) || data.length === 0) {
      errors.push('Excel文件中没有找到数据');
      return { validatedData, errors };
    }
    
    // 检查必要的列
    const firstRow = data[0];
    const requiredColumns = ['学号', '姓名', '性别', '年级', '班级', '出生日期'];
    const missingColumns = requiredColumns.filter(col => !Object.keys(firstRow).includes(col));
    
    if (missingColumns.length > 0) {
      errors.push(`缺少必要的列: ${missingColumns.join(', ')}`);
      return { validatedData, errors };
    }
    
    // 验证每行数据
    data.forEach((row, index) => {
      const rowErrors: string[] = [];
      const studentData: any = {};
      
      // 学号验证
      const studentId = row['学号'];
      if (!studentId || typeof studentId !== 'string' || studentId.toString().trim() === '') {
        rowErrors.push('学号不能为空');
      } else {
        const trimmedId = studentId.toString().trim();
        if (existingStudentIds.has(trimmedId)) {
          rowErrors.push(`学号 ${trimmedId} 已存在`);
        }
        studentData.studentId = trimmedId;
      }
      
      // 姓名验证
      const name = row['姓名'];
      if (!name || typeof name !== 'string' || name.toString().trim() === '') {
        rowErrors.push('姓名不能为空');
      }
      studentData.name = name ? name.toString().trim() : '';
      
      // 性别验证
      const gender = row['性别'];
      if (gender === '男' || gender === 'male') {
        studentData.gender = 'male';
      } else if (gender === '女' || gender === 'female') {
        studentData.gender = 'female';
      } else {
        rowErrors.push('性别必须为男或女');
      }
      
      // 年级验证和转换
      const grade = row['年级'];
      if (grade === '高一' || grade === 'freshman') {
        studentData.grade = 'freshman' as GradeLevel;
      } else if (grade === '高二' || grade === 'sophomore') {
        studentData.grade = 'sophomore' as GradeLevel;
      } else if (grade === '高三' || grade === 'junior') {
        studentData.grade = 'junior' as GradeLevel;
      } else {
        rowErrors.push('年级必须为高一、高二或高三');
      }
      
      // 班级验证和转换（根据班级名称查找班级ID）
      const className = row['班级'];
      if (!className) {
        rowErrors.push('班级不能为空');
      } else {
        // 尝试精确匹配或包含匹配
        const classInfo = classes.find(c => 
          c.name === className || 
          c.name === `${className}` || 
          c.name.includes(className.toString())
        );
        
        if (!classInfo) {
          rowErrors.push(`找不到班级: ${className}`);
        } else {
          studentData.classId = classInfo.id;
        }
      }
      
      // 出生日期验证
      const dateOfBirth = row['出生日期'];
      if (!dateOfBirth) {
        rowErrors.push('出生日期不能为空');
      } else {
        // 尝试解析日期
        const parsedDate = parseDate(dateOfBirth);
        if (!parsedDate) {
          rowErrors.push('出生日期格式不正确');
        } else {
          // 确保是ISO格式
          studentData.dateOfBirth = new Date(parsedDate).toISOString();
        }
      }
      
      // 入学日期处理
      const admissionDate = row['入学日期'];
      if (admissionDate) {
        const parsedDate = parseDate(admissionDate);
        if (parsedDate) {
          studentData.admissionDate = new Date(parsedDate).toISOString();
        } else {
          rowErrors.push('入学日期格式错误');
          studentData.admissionDate = new Date().toISOString(); // 默认当前日期
        }
      } else {
        // 默认设置为当前日期
        studentData.admissionDate = new Date().toISOString();
      }
      
      // 联系电话处理
      studentData.phoneNumber = row['联系电话'] ? row['联系电话'].toString().trim() : '';
      
      // 电子邮箱处理
      studentData.email = row['电子邮箱'] ? row['电子邮箱'].toString().trim() : '';
      
      // 家庭住址处理
      studentData.address = row['家庭住址'] ? row['家庭住址'].toString().trim() : '';
      
      // 宿舍信息处理
      studentData.dormitory = row['宿舍'] ? row['宿舍'].toString().trim() : '';
      
      // 状态处理
      const status = row['状态'];
      if (status === '在读' || status === 'active') {
        studentData.status = 'active' as StudentStatus;
      } else if (status === '毕业' || status === 'graduated') {
        studentData.status = 'graduated' as StudentStatus;
      } else if (status === '转学' || status === 'transferred') {
        studentData.status = 'transferred' as StudentStatus;
      } else if (status === '休学' || status === 'suspended') {
        studentData.status = 'suspended' as StudentStatus;
      } else {
        studentData.status = 'active' as StudentStatus; // 默认状态
      }
      
      // 添加必要字段的默认值
      if (!studentData.dateOfBirth) studentData.dateOfBirth = new Date().toISOString();
      if (!studentData.admissionDate) studentData.admissionDate = new Date().toISOString();
      if (!studentData.phoneNumber) studentData.phoneNumber = '';
      if (!studentData.email) studentData.email = '';
      if (!studentData.address) studentData.address = '';
      if (!studentData.dormitory) studentData.dormitory = '';
      
      if (rowErrors.length > 0) {
        errors.push(`第 ${index + 2} 行数据错误: ${rowErrors.join(', ')}`);
      } else {
        // 只在验证通过时添加ID
        studentData.id = Date.now().toString() + Math.random().toString(36).substr(2, 9) + index;
        validatedData.push(studentData);
      }
    });
    
    // 如果有验证通过的数据但有部分行错误，添加汇总消息
    if (validatedData.length > 0 && errors.length > 0) {
      errors.unshift(`共 ${data.length} 条数据，${validatedData.length} 条验证通过，${errors.length} 条验证失败`);
    }
    
    return { validatedData, errors };
  };

  // 处理文件上传
  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    
    const reader = new FileReader();
    reader.onload = (event) => {
      try {
        const data = new Uint8Array(event.target?.result as ArrayBuffer);
        const workbook = XLSX.read(data, { type: 'array' });
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        
        // 将Excel数据转换为JSON
        const jsonData = XLSX.utils.sheet_to_json(worksheet);
        
        // 验证数据格式
        const { validatedData, errors } = validateImportData(jsonData);
        setImportData(validatedData);
        setImportErrors(errors);
        
      } catch (error) {
        console.error('解析Excel文件失败:', error);
        setImportErrors(['解析Excel文件失败，请检查文件格式']);
      }
    };
    reader.readAsArrayBuffer(file);
  };

  // 确认导入数据
  const confirmImportData = async () => {
    if (importData.length === 0) return;
    
    setIsImporting(true);
    let successCount = 0;
    const importFailures: string[] = [];
    
    // 导入数据（使用异步方式确保正确处理）
    for (let i = 0; i < importData.length; i++) {
      try {
        const studentData = importData[i];
        // 确保所有字段名和类型正确
        // 查找班级信息以获取学院
        const classInfo = classes.find(c => c.id === studentData.classId);
        const formattedData = {
          // 移除id，让createStudent方法自动生成
          studentId: studentData.studentId,
          name: studentData.name,
          gender: studentData.gender,
          grade: studentData.grade,
          classId: studentData.classId.toString(), // 确保classId是string类型
          // 根据班级自动设置学院，确保与班级管理中的学院一致
          academy: classInfo?.academy || '',
          dateOfBirth: studentData.dateOfBirth ? new Date(studentData.dateOfBirth).toISOString() : new Date().toISOString(),
          admissionDate: studentData.admissionDate ? new Date(studentData.admissionDate).toISOString() : new Date().toISOString(),
          phoneNumber: studentData.phoneNumber || '',
          email: studentData.email || '',
          address: studentData.address || '',
          dormitoryId: studentData.dormitory || '', // 修改为dormitoryId以匹配数据模型
          status: studentData.status || 'active'
        };
        
        // 使用DataContext中的createStudent方法实际保存数据
        await dataContext.createStudent(formattedData);
        successCount++;
        console.log('成功导入学生数据:', formattedData.studentId);
        
      } catch (error) {
        console.error(`导入第${i+1}条数据失败:`, error);
        importFailures.push(`学号 ${studentData.studentId}: ${studentData.name} 导入失败`);
      }
    }
    
    setImportSuccess(successCount);
    if (importFailures.length > 0) {
      setImportErrors([...importErrors, ...importFailures.slice(0, 10)]); // 只显示前10个失败记录
    }
    setIsImporting(false);
    
    // 调用导入完成回调
    if (onImportComplete) {
      onImportComplete();
    }
  };

  // 下载导入模板
  const handleDownloadTemplate = () => {
    // 创建模板数据
    const templateData = [
      {
        '学号': '2024001',
        '姓名': '张三',
        '性别': '男',
        '年级': '高一',
        '班级': '高一(1)班',
        '出生日期': '2006-01-01',
        '入学日期': '2024-09-01',
        '联系电话': '13800138001',
        '电子邮箱': 'zhangsan@example.com',
        '家庭住址': '北京市海淀区',
        '宿舍': '男生宿舍3栋401',
        '状态': '在读'
      }
    ];
    
    // 创建工作簿和工作表
    const ws = XLSX.utils.json_to_sheet(templateData);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, '学生数据导入模板');
    
    // 导出Excel文件
    XLSX.writeFile(wb, '学生数据导入模板.xlsx');
  };

  // 关闭导入模态框
  const handleClose = () => {
    setImportData([]);
    setImportErrors([]);
    setImportSuccess(0);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className="modal-overlay">
      <div className="modal-content import-modal">
        <div className="modal-header">
          <h2>导入学生数据</h2>
          <button className="modal-close" onClick={handleClose}>
            ×
          </button>
        </div>
        
        <div className="modal-body">
          {!importSuccess && (
            <>
              <div className="import-instructions">
                <h3>导入说明</h3>
                <ul>
                  <li>请确保Excel文件格式正确，包含必要的列：学号、姓名、性别、年级、班级、出生日期</li>
                  <li>可选列：入学日期、联系电话、电子邮箱、家庭住址、宿舍</li>
                  <li>支持的文件格式：.xlsx, .xls</li>
                  <li>年级支持：高一、高二、高三</li>
                  <li>性别支持：男、女</li>
                  <li>状态支持：在读、毕业、转学、休学（默认为在读）</li>
                </ul>
              </div>
              
              <div className="import-actions">
                <input
                  type="file"
                  ref={fileInputRef}
                  accept=".xlsx,.xls"
                  onChange={handleFileUpload}
                  style={{ display: 'none' }}
                />
                <button 
                  className="btn-secondary"
                  onClick={() => fileInputRef.current?.click()}
                >
                  选择文件
                </button>
                <button 
                  className="btn-secondary"
                  onClick={handleDownloadTemplate}
                >
                  下载模板
                </button>
              </div>
              
              {/* 显示验证错误 */}
              {importErrors.length > 0 && (
                <div className="import-errors">
                  <h3>数据验证错误</h3>
                  <ul>
                    {importErrors.map((error, index) => (
                      <li key={index}>{error}</li>
                    ))}
                  </ul>
                </div>
              )}
              
              {/* 显示待导入数据预览 */}
              {importData.length > 0 && importErrors.length === 0 && (
                <div className="import-preview">
                  <h3>待导入数据预览 ({importData.length} 条)</h3>
                  <div className="preview-table-container">
                    <table className="preview-table">
                      <thead>
                        <tr>
                          <th>学号</th>
                          <th>姓名</th>
                          <th>性别</th>
                          <th>年级</th>
                          <th>班级</th>
                          <th>出生日期</th>
                        </tr>
                      </thead>
                      <tbody>
                        {importData.slice(0, 5).map((student, index) => (
                          <tr key={index}>
                            <td>{student.studentId}</td>
                            <td>{student.name}</td>
                            <td>{student.gender === 'male' ? '男' : '女'}</td>
                            <td>{student.grade === 'freshman' ? '高一' : student.grade === 'sophomore' ? '高二' : '高三'}</td>
                            <td>{classes.find(c => c.id === student.classId)?.name}</td>
                            <td>{student.dateOfBirth}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                  {importData.length > 5 && (
                    <p className="preview-more">... 还有 {importData.length - 5} 条数据未显示</p>
                  )}
                </div>
              )}
            </>
          )}
          
          {/* 导入结果显示 */}
          {importSuccess > 0 && (
            <div className="import-result">
              <h3>导入完成</h3>
              <p>成功导入 {importSuccess} 条学生数据</p>
              {importSuccess !== importData.length && (
                <p className="warning">部分数据导入失败，请检查错误信息</p>
              )}
            </div>
          )}
        </div>
        
        <div className="modal-footer">
          {!importSuccess ? (
            <>
              <button 
                className="btn-cancel" 
                onClick={handleClose}
              >
                取消
              </button>
              <button 
                className="btn-primary" 
                onClick={confirmImportData}
                disabled={importData.length === 0 || importErrors.length > 0 || isImporting}
              >
                {isImporting ? '导入中...' : '确认导入'}
              </button>
            </>
          ) : (
            <button 
              className="btn-primary" 
              onClick={handleClose}
            >
              关闭
            </button>
          )}
        </div>
      </div>
    </div>
  );
};

export default ImportModal;